﻿using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Model.UI;
using CoreShop.Services;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using SqlSugar.Extensions;
using Sunny.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Windows.Forms;
using System.Linq;
using Sunny.UI.Win32;
using Yitter.IdGenerator;
using static CoreShop.Library.GlobalEnumVars;
using CoreShop.PrintService;
using CoreShop.Model.FromBody;
using CoreShop.Services.Services.System;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using System.Drawing;
using CoreShop.App.Units.Interface;
using Loading;

namespace CoreShop.App
{
    public partial class frmUserDeposit : BaseForm
    {
        public corecmsuser member = null;
        public corecmsuserdepositrules deposit = null;
        public List<TopUpItemDataInfoMode> deposits;
        public TopUpItemDataInfoMode deposititem = null;
        OpaqueCommand cmd = new OpaqueCommand();
        public frmUserDeposit(corecmsuser _member)
        {
            InitializeComponent();
            member = _member;
            txtGiftAmout.TextBox.GotFocus += txtGiftAmout_GotFocus;
            txtAmout.TextBox.GotFocus += txtAmout_GotFocus;
        }

        private void txtNumber_GotFocus(object sender, System.EventArgs e)
        {
            numPad.SetTextBox((UIEdit)sender, UITextBox.UIEditType.String, 0);
        }

        private void txtAmout_GotFocus(object sender, System.EventArgs e)
        {
            numPad.SetTextBox((UIEdit)sender, UITextBox.UIEditType.Double, 2);
        }

        private void txtGiftAmout_GotFocus(object sender, System.EventArgs e)
        {
            numPad.SetTextBox((UIEdit)sender, UITextBox.UIEditType.Double, 2);
        }

        private void frmSetBalance_Load(object sender, EventArgs e)
        {
            this.uiLine1.FillColor = System.Drawing.Color.White;
            this.uiLine1.LineColor = System.Drawing.Color.Gainsboro;
            this.uiLine3.FillColor = System.Drawing.Color.White;
            this.uiLine3.LineColor = System.Drawing.Color.Gainsboro;
            SetMemberInfo();
            LoadPaymentList();            
        }

        private void LoadPaymentList()
        {
            if ((AppConstVars.sysPayments == null) || (AppConstVars.sysPayments.Count == 0))
                ProcessUtil.GetSystemPayment();//打开支付方式表

            var payList = AppConstVars.sysPayments
                .Where(p => p.isEnable == true && p.rechargeUsed == 1 && p.id != (int)GlobalEnumVars.Payment.balancepay && p.id != (int)GlobalEnumVars.Payment.coupon)
                .OrderBy(p => p.sort).ToList();

            if (payList.Count == 0)
            {
                UIMessageBox.Show("没有选择支付方式。");
                this.Close();
            }
            else
            {
                foreach (var pay in payList)
                {
                    CreatePaymentBtn(pay);
                }
                if (payList.Count > 0)
                {
                    var payItem = payList[0];
                    btnCash_Click(GetButtonByID(payItem.id), null);
                }
            }         
        }

        private UISymbolButton GetButtonByID(int payId)
        {
            var mControl = layPaymentList.Get(PaymentUtil.GetPayItemName(payId));
            var btnSend = (UISymbolButton)mControl;
            return btnSend;
        }

        /// <summary>
        /// 建支付按钮
        /// </summary>
        /// <param name="index"></param>
        private void CreatePaymentBtn(corecmspayments payInfo)
        {
            UISymbolButton btn = new UISymbolButton();
            btn.Name = PaymentUtil.GetPayItemName(payInfo.id);
            btn.Size = payItemName.Size;
            btn.FillColor = payItemName.FillColor;
            btn.FillColor2 = payItemName.FillColor2;
            btn.Font = payItemName.Font;
            btn.ForeColor = payItemName.ForeColor;
            if (CommFunc.ConvertToInt32(payInfo.symbol) > 0)
                btn.Symbol = CommFunc.ConvertToInt32(payInfo.symbol);
            else
                btn.Symbol = 157471;
            btn.ForeSelectedColor = payItemName.ForeSelectedColor;
            btn.ImageAlign = payItemName.ImageAlign;
            btn.RectColor = payItemName.RectColor;
            btn.SymbolColor = payItemName.SymbolColor;
            btn.SymbolOffset = payItemName.SymbolOffset;
            btn.TextAlign = payItemName.TextAlign;
            btn.Padding = payItemName.Padding;
            btn.Text = payInfo.name;
            btn.Click += btnCash_Click;
            btn.Tag = payInfo.id;
            layPaymentList.Add(btn);
        }

        public void AddLevelItems(List<TopUpItemDataInfoMode> items)
        {
            foreach (var RechargeInfo in  items)
            {
                DishItemInfo dish = new DishItemInfo();
                dish.Name = RechargeInfo.rechargeStandardName;
                //if (CommFunc.ConvertToDecimal(member.sumBalance) == 0)
                if (RechargeInfo.isFirst == 0)                
                    dish.Money = string.IsNullOrEmpty(RechargeInfo.amountFirstZ) ? "" : "首充赠金" + CommFunc.ConvertToDecimal(RechargeInfo.amountFirstZ).ToString() + "元";
                else
                    dish.Money = string.IsNullOrEmpty(RechargeInfo.amountZ.ToString()) ? "" : string.Format(@"赠{0}元", CommFunc.ConvertToDecimal(RechargeInfo.amountZ));

                dish.UnitName = "";
                var item = new UIDishItemList(dish);
                item.Name = RechargeInfo.rechargeStandardId;
                item.Visible = true;
                item.Margin = new System.Windows.Forms.Padding(3);
                item.Tag = RechargeInfo.rechargeStandardId;
                item.Click += Item_Click;
                fly_foodlist.Add(item);
            }            
        }

        private void Item_Click(object sender, System.EventArgs e)
        {
            UIDishItemList item = (UIDishItemList)sender;
            deposititem = deposits.Find(p => p.rechargeStandardId == item.Tag.ToString());
            if (deposititem != null)
            {
                txtAmout.Text = deposititem.amount.ToString();
                if (deposititem.isFirst == 0)
                    txtGiftAmout.Text = deposititem.amountFirstZ.ToString();
                else
                    txtGiftAmout.Text = deposititem.amountZ.ToString();
                txtGiftAmout.Enabled = false;
                txtAmout.Enabled = false;
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            MessageBox.Show("支付信息不存。");
            //bool check = CheckData1();
        }

        private void btnCash_Click(object sender, EventArgs e)
        {
            try
            {
                if (sender == null) return;
                (sender as UISymbolButton).Selected = true;
                var mPayID = CommFunc.ConvertToInt32((sender as UISymbolButton).Tag);
                var payment = AppConstVars.sysPayments.Find(p => p.id == mPayID);
                if (payment == null)
                {
                    UIMessageBox.Show("没有找到该付款方式的信息。");
                    return;
                }
                foreach (var pay in AppConstVars.sysPayments)
                {
                    var mControl = layPaymentList.Get(PaymentUtil.GetPayItemName(pay.id));
                    if (mControl != null)
                    {
                        var item = (UISymbolButton)mControl;
                        item.Selected = false;
                    }
                }
                UISymbolButton itemSelect = (UISymbolButton)sender;
                (sender as UISymbolButton).Selected = true;
                txtPayName.Text = payment.name;                
                txtPayName.Tag = mPayID;
                txtAmout.Focus();
                double amount = CommFunc.ConvertToDouble(txtAmout.Text);
                if (amount > 0) numPad_OKButtonClick(this.numPad, txtAmout.Text, 0, amount);
            }
            catch { }
        }

        private void SetMemberInfo()
        {
            balance.Text = "0.00";
            point.Text = "0";
            foreach (Control ctr in this.FindForm().Controls)
            {
                if (ctr is Label)
                {
                    Label lb = ctr as Label;
                    if (CommFunc.ConvertToString(lb.Tag) == "field")
                    {
                        lb.Text = "";
                    }
                }
            }
            if (member == null) return;
            balance.Text = member.balance.ToString();
            point.Text = CommFunc.ConvertToInt32(member.point).ToString();
            ControlsDataBinding.ValueBind(member, this);
            status.Text = EnumHelper.GetEnumByValue<GlobalEnumVars.MemberStatus>(member.status ?? 1);
            corecmsusercategory memberCategory = new corecmsusercategoryServices().GetById(member.userCategoryId);
            corecmsusergrade memberGrade = new corecmsusergradeServices().GetById(member.grade);
            if (memberGrade != null)
            {
                grade.Text = memberGrade.title;
                discountValue.Text = memberGrade.discountValue.ToString();
            }
            status.Text = EnumHelper.GetEnumByValue<GlobalEnumVars.MemberStatus>(member.status.ObjToInt(0));
        }

        private void txtAmout_ButtonClick(object sender, EventArgs e)
        {
            txtAmout.Text = "";
            txtAmout.Focus();
        }

        private bool SetMobilePay(corecmsuserbalance balance)
        {
            if ((balance.paymentId == (int)GlobalEnumVars.Payment.alipay) 
                || (balance.paymentId == (int)GlobalEnumVars.Payment.wechatpay)
                || (balance.paymentId == (int)GlobalEnumVars.Payment.paymix))
            {
                var orderpayment = new corecmsfoodorderpayment();
                orderpayment.paymentId = balance.paymentId;
                orderpayment.payAmount = balance.money - balance.giftAmount;
                orderpayment.takeAmount = balance.money - balance.giftAmount;
                var bl = PaymentUtil.SetPaymentMobile(orderpayment);
                if (!bl) return false;
                balance.paymentCode = orderpayment.paymentCode;
                balance.paymentId = orderpayment.paymentId;
            }
            return true;
        }

        private async void numPad_OKButtonClick(object sender, string text, int intvalue, double doublevalue)
        {
            if (AppConstVars.classId == 0)
            {
                ProcessUtil.GetClassData(AppConstVars.sysUser.id);
                if (AppConstVars.classId == 0)
                {
                    UIMessageBox.Show("当前用户没有当班,无法充值", "系统提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }
            }

            decimal amount = CommFunc.ConvertToDecimal(txtAmout.Text);
            if ((string.IsNullOrEmpty(txtAmout.Text)) || (amount == 0) || (amount > 999999))
            {
                MessageBox.Show("没有输入充值金额或金额有不合规的数值。");
                txtAmout.Focus();
                return;
            }
            if ((member == null) || (member.id == 0))
            {
                UIMessageBox.Show("没有选择要充值的会员。");
                txtAmout.Focus();
                return;
            }
            var mPayID = CommFunc.ConvertToInt32(txtPayName.Tag);
            var sysPayment = new corecmspaymentsService().SelectDataById(mPayID);
            if (sysPayment == null)
            {
                UIMessageBox.Show("支付信息不存在。");
                txtAmout.Focus();
                return;
            }

            try
            {
                cmd.ShowOpaqueLayer(pnl_Form, 125, true);
                decimal giftAmount = CommFunc.ConvertToDecimal(txtGiftAmout.Text);
                corecmsuserbalance balance = new corecmsuserbalance();
                balance.id = CommFunc.GetCorpNextId(AppConstVars.sysUser.corpId, YitIdHelper.NextId());
                balance.orderId = CommonHelper.GetSerialNumberType((int)GlobalEnumVars.SerialNumberType.会员充值消费编号);
                balance.userId = member.id;
                balance.vipNo = member.mobile;
                balance.classId = AppConstVars.classId;
                balance.type = (int)GlobalEnumVars.UserBalanceTypes.Deposit;
                balance.direction = 1;
                balance.storeId = AppConstVars.sysUser.storeId;
                balance.realAmount = amount;
                balance.money = amount + giftAmount;
                balance.giftAmount = giftAmount;
                balance.balance = 0;
                balance.giftBalance = 0;
                balance.sourceId = 0;
                balance.memo = "";
                balance.createTime = DateTime.Now;
                balance.corpId = AppConstVars.sysUser.corpId;
                balance.cardItemId = 0;
                balance.quantity = 0;
                balance.balanceQuantity = 0;
                balance.sysUserId = AppConstVars.sysUser.id;
                balance.sysUserName = AppConstVars.sysUser.userName;
                balance.paymentId = mPayID;
                balance.payName = txtPayName.Text;
                balance.paymentCode = "";
                balance.payStatus = (int)GlobalEnumVars.OrderPayStatus.UnPay;
                balance.status = (int)GlobalEnumVars.BalanceStatus.UnCheck;               

                if (new corecmsuserbalanceServices().InsertAsync(balance))
                {
                    if (!SetMobilePay(balance)) return;

                    var orderBusiness = new OrderBusiness();

                    PosOrderHeadDto postData = orderBusiness.GetUserDepositData(balance, AppConstVars.sysUser, AppConstVars.sysStore, AppConstVars.classNumber, (int)OrderBillType.Deposit);
                    string paymentCode = balance.paymentCode;
                    postData.billVipPromo = orderBusiness.CreateBillVipPromoDto(postData.orderId, deposititem); 
                    var res = await OrderApiUtil.SendOrderAsync(postData);
                    if (res == null)
                    {
                        UIMessageBox.Show("提交数据失败，请重试。");
                        txtAmout.Focus();
                        return;
                    }
                    if (res.code == 200)
                    {
                        member.balance = balance.balance;
                        member.giftBalance = balance.giftBalance;
                        new corecmsuserServices().UpdateAsync(member);
                        balance.payStatus = (int)GlobalEnumVars.OrderPayStatus.IsPay;
                        balance.status = (int)GlobalEnumVars.BalanceStatus.IsCheck;
                        balance.paymentTime = DateTime.Now;
                        balance.paymentCode = paymentCode;
                        balance.sysUserName = AppConstVars.sysUser.userName;
                        new corecmsuserbalanceServices().UpdateAsync(balance);

                        new PrintServices().SetUserDepositBill(balance, member, false);

                        UIMessageBox.Show("充值成功", "系统提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    }
                    else
                    {
                        UIMessageBox.Show("充值失败" + res.msg, "系统提示", UIStyle.Red, UIMessageBoxButtons.OK);
                        return;
                    }
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                }
                else
                {
                    UIMessageBox.Show("充值失败", "系统提示", UIStyle.Red, UIMessageBoxButtons.OK);
                    return;
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.Show("获取卡类型失败:。" + ex.Message);
            }
            finally { cmd.HideOpaqueLayer(); }            
        }

        private void txtAmout_TextChanged(object sender, EventArgs e)
        {
            this.txtGiftAmout.Clear();
            txtAmout.ShowButton = !string.IsNullOrEmpty(this.txtAmout.Text);
            var rechargeMoney = CommFunc.ConvertToDecimal(this.txtAmout.Text);
            if (rechargeMoney == 0)
            {
                this.txtGiftAmout.Text = "";
                return;
            }
            if (deposits.Count > 0)
            {                
                var nowTime = DateTime.Now;
                //查询可参与的充值活动                
                var deposititem = deposits.Find(p => p.amount % rechargeMoney == 0 && p.amount > rechargeMoney);
                if (deposititem != null)
                {
                    decimal accumulationCount = 0;
                    bool isMultiple = rechargeMoney % deposititem.amount == 0;
                    if (isMultiple)
                    {
                        accumulationCount = rechargeMoney / deposititem.amount;
                    }
                    if (accumulationCount > 0)//满足条件
                    {
                        this.txtGiftAmout.Text = (accumulationCount * deposititem.amountZ).ToString();
                    }
                }
            }
        }

        private async void frmUserDeposit_Shown(object sender, EventArgs e)
        {
            try
            {
                cmd.ShowOpaqueLayer(pnl_Form, 125, true);
                var result = await MemberApiUtil.GetMemberTopUpItem(AppConstVars.sysUser, member.id.ToString());
                deposits = result.data;
                AddLevelItems(deposits);
            }
            catch (Exception ex)
            {
                //HideWaitForm();
                ShowSuccessTip("获取卡类型失败:。" + ex.Message);
            }
            finally { cmd.HideOpaqueLayer(); }
            txtAmout.Focus();
        }

        private void txtAmout_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 12290)
            {
                string str = txtAmout.Text;
                int idx = txtAmout.SelectionStart;
                str = str.Insert(idx, ".");
                txtAmout.Text = str;
                txtAmout.SelectionStart = idx + 1;
                txtAmout.Focus();
                e.Handled = true;
            }
        }

        private void txtGiftAmout_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 12290)
            {
                string str = txtGiftAmout.Text;
                int idx = txtGiftAmout.SelectionStart;
                str = str.Insert(idx, ".");
                txtGiftAmout.Text = str;
                txtGiftAmout.SelectionStart = idx + 1;
                txtGiftAmout.Focus();
                e.Handled = true;
            }
        }
    }
}
